package cn.liberals.basic.utils;

import cn.liberals.basic.jwt.JwtUtils;
import cn.liberals.basic.jwt.Payload;
import cn.liberals.basic.jwt.RsaUtils;
import cn.liberals.basic.jwt.UserInfo;
import cn.liberals.user.domain.Logininfo;
import cn.liberals.basic.utils.JwtRasHolder;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * @Description: 登录的上下文
 * @Author: Mr.She
 * @Version: 1.0
 * @Date:  2022/7/16 9:26
 */
@Slf4j
public class LoginContext {

    /**
     * @Title: getLogininfo
     * @Description: 获取到登录用户的logininfo
     * @Author: Mr.She
     * @Version: 1.0
     * @Date:  2022/7/16 9:27
     * @Parameters: []
     * @Return cn.liberals.user.domain.Logininfo
     */
    public static Logininfo getLogininfo(HttpServletRequest req) {
        try {
            // 1.从请求头中获取token，判断是否存在
            String token = req.getHeader("token");
            // 1.解析token得到载荷数据
            PublicKey publicKey = RsaUtils.getPublicKey(JwtRasHolder.INSTANCE.getJwtRsaPubData());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            // 2.判断载荷数据不为空时，说明已经是登录成功了，那么就不拦截
            if (payload == null){
                log.error("getLogininfo error...");
                return null;
            }
            return payload.getUserInfo().getLogininfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 最好在此登录上下文类中多封装几个工具方法
    // 1.根据req得到user对象，根据req得到employee对象，根据req得到shop对象
}